#include "common.h"
#include <Windows.h>
#include "stdio.h"
#include "crtdefs.h"
#include <time.h>


namespace cupid
{

#define MAX_LEN         1024


void log(const char * szFormat, ...)
{

#ifdef _DEBUG
	char szBuf[MAX_LEN];

	va_list ap;
	va_start(ap, szFormat);
	vsnprintf_s(szBuf, MAX_LEN, MAX_LEN, szFormat, ap);
	va_end(ap);

	//FILE * file;
	//fopen_s(&file, "debug.log", "a");
	//fseek(file, 0, SEEK_END);
	//fwrite("\n", 1, 1, file);
	//fputs(szBuf, file);
	//fclose(file);
#endif

}

string format_str(const char * szFormat, ...)
{
	char szBuf[MAX_LEN];

	va_list ap;
	va_start(ap, szFormat);
	vsnprintf_s(szBuf, MAX_LEN, MAX_LEN, szFormat, ap);
	va_end(ap);
	return szBuf;
}

int	str2int(string str)
{
	return atoi(str.c_str());
}



int	splitPacket(const char* buf, int bufLen, int* packet, char** msg, int* msgSize)
{
	if(bufLen > PROTOCOL_MSG_HEADSIZE)
	{
		CProtocolMsgStruct*	msgPtr = (CProtocolMsgStruct*)buf;
		if(msgPtr->msgSize <= bufLen)
		{
			if(msgPtr->msgSize < 4 || msgPtr->msgSize > MAX_PACKETSIZE)
				return 0;

			*packet		= msgPtr->idPacket;
			*msgSize	= msgPtr->msgSize /*- PROTOCOL_MSG_HEADSIZE*/;
			*msg		= const_cast<char*>(buf); /*msgPtr->msg;*/
			return msgPtr->msgSize;
		}
	}
	return 0;
}


int	unitePacket(char* buf, int bufLen, int packet, const char* msg, int msgSize)
{
	if(bufLen >= msgSize + PROTOCOL_MSG_HEADSIZE)
	{
		CProtocolMsgStruct*	msgPtr = (CProtocolMsgStruct*)buf;
		msgPtr->idPacket		= (unsigned short)packet;
		msgPtr->msgSize		= msgSize /*+ PROTOCOL_MSG_HEADSIZE*/;
		memcpy(buf,	msg, (size_t)msgSize);
		return msgPtr->msgSize;
	}
	return 0;
}


bool initSocket()
{

	WSADATA		wsaData;
	int ret = WSAStartup(0x0002, &wsaData);			// 0x0101
	if(ret!=0)
	{
		log("ERROR: Init WSAStartup() failed.");
		return false;
	}

	if(wsaData.wVersion != 0x0002)				// 0x0101
	{
		log("ERROR: WSAStartup Version not match 2.0");		// 1.1
		return false;
	}

	return true;
}

/////////////////////////////////////////////////////////////////////////////////
bool cleanSocket()
{
	WSACleanup();
	return true;
}

int getGUID()
{
	return _time32(NULL);
}

int getTime()
{
	return _time32(NULL);
}
}